import { Form, Input, message, Modal, Button } from 'antd';
import React, { useState, useEffect } from 'react';
import styles from './index.less';
import { updataProject, IntlInit, snake2camel } from '@/services/utils';
import type { Project } from '@/services/web/models/';
import { IntlInitJsx } from '@/components/PPIntl';
import { ProjectApi, Configuration } from '@/services/web'; // 引入 ProjectApi 类

type PPExportProps = {
    project: Project;
    visible?: boolean;
};

const baseUrl = localStorage.getItem('basePath');

const PPUpdataModal: React.FC<PPExportProps> = (props) => {
    const config = new Configuration(baseUrl ? { basePath: baseUrl } : undefined);
    const intl = IntlInit('component.PPUpdataModal');
    const intlJsx = IntlInitJsx('component.PPUpdataModal');
    const [loading, setLoading] = useState<boolean>(false);
    const [visible, setVisible] = useState<boolean>(props.visible || false);
    const [form] = Form.useForm();
    const projectApi = new ProjectApi(config);

    console.log("进入PPUpdataModal");
    console.log("props.project", props.project);

    const [isChecking, setIsChecking] = useState<boolean>(() => {
        const storedIsChecking = localStorage.getItem('isChecking');
        return storedIsChecking === 'true';
    });

    useEffect(() => {
        localStorage.setItem('isChecking', isChecking.toString());
    }, [isChecking]);

    useEffect(() => {
        let intervalId: NodeJS.Timeout;

        const checkUpdateResult = async () => {
            try {
                const result = await projectApi.updata_result(props.project.project_id);
                if (result && result.message === "更新完成") {
                    message.success("项目更新完成");
                    clearInterval(intervalId);
                    setIsChecking(false); // 停止定时器
                }
            } catch (error) {
                console.error("检查更新结果失败:", error);
            }
        };

        if (isChecking) {
            intervalId = setInterval(checkUpdateResult, 5000);
        }

        return () => {
            clearInterval(intervalId);
        };
    }, [isChecking, props.project.project_id]);

    const handleExport = (values: any) => {
        setLoading(true);
        updataProject(props.project.project_id, values.path)
            .then((res) => {
                console.log("updata_test", res);
                message.success(res.message);
                setIsChecking(true); // 启动定时器
                setVisible(false);
            })
            .catch((err) => {
                console.error(err);
            })
            .finally(() => {
                setLoading(false);
            });
    };

    return (
        <span>
            <Button type="primary" onClick={() => setVisible(true)}>
                {intlJsx('title')}
            </Button>
            <Modal
                className={styles.modal}
                title={intlJsx('title')}
                visible={visible}
                onCancel={() => setVisible(false)}
                footer={null}
            >
                <Form
                    form={form}
                    name="basic"
                    labelCol={{ span: 6 }}
                    wrapperCol={{ span: 16 }}
                    initialValues={{ remember: false }}
                    onFinish={handleExport}
                    autoComplete="off"
                >
                    <Form.Item
                        label={intl('path')}
                        name="path"
                        rules={[{ required: true, message: intlJsx('nullPath') }]}
                    >
                        <Input />
                    </Form.Item>

                    <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
                        <Button
                            onClick={() => {
                                setVisible(false);
                                form.resetFields();
                            }}
                        >
                            {intlJsx('cancel', 'global')}
                        </Button>
                        <Button type="primary" htmlType="submit" loading={loading}>
                            {intlJsx('export')}
                        </Button>
                    </Form.Item>
                </Form>
            </Modal>
        </span>
    );
};

export default PPUpdataModal;